import {enMqtt, mqttUrl} from "~/url";
const mqtt = require("./libs/mqtt.min.4.2.1");
const app = getApp();

class MqttUtils {
    _client = null;
    _host = mqttUrl;
    _options = {
        username: "applet",
        password: "",
        reconnectPeriod: 1000, // 1000毫秒，设置为 0 禁用自动重连，两次重新连接之间的间隔时间
        connectTimeout: 10 * 1000, // 10秒，连接超时时间
        keepalive: 60,
        language: "zh",
    };
    _subTopic = [];

    init(options) {
        const that = this;
        that._options = {
            clientId: new Date().getTime(),
            ...that._options,
            ...options,
        };
    }

    connect() {
        const that = this;
        if (!enMqtt || that.isConnected()){ return; }
        try {
            that._client = mqtt.connect(`${that._host}`, that._options);
            that._client.on("connect", () => {
                console.log("onConnect");
                BusUtils.$emit("mqttConnect")
            });
            that._client.on("message", (topic, payload) => {
                console.log("onMessage", topic, payload.toString());
                app.bus.$emit("mqttMessage", {
                    topic,
                    payload,
                })
            });
            that._client.on("error", (error) => {
                console.log("onError", error);
                app.bus.$emit("mqttError", { error })
            });
            that._client.on("reconnect", () => {
                console.log("reconnecting...");
                app.bus.$emit("mqttReconnect")
            });
            that._client.on("offline", () => {
                console.log("onOffline");
                app.bus.$emit("mqttOffline")
            });
            that._client.on("close", () => {
                console.log("onClose");
                that._client = null;
            });
        }catch (e) {
            console.log("mqtt init error", e);
        }
    }

    subscribe(topic) {
        const that = this;
        if (!enMqtt || !that.isConnected()) { return; }
        if (that.isConnected() && !that._subTopic.includes(topic)){
            that._subTopic.push(topic);
            that._client.subscribe(topic, { qos: 0 }, function (error, granted) {
                if (error) {
                    console.log(error)
                } else {
                    console.log(`${granted[0].topic} was subscribed`)
                }
            });
        }else{
            console.log("subscribe error: mqtt not connect OR topic already subscribe ");
        }
    }

    publish(topic, msg) {
        const that = this;
        if (!enMqtt || !that.isConnected()) { return; }
        if (that.isConnected()){
            that._client.publish(topic, msg, { qos: 2 });
        }
    }

    isConnected() {
        const that = this;
        return that._client && that._client?.connected && that._client?.disconnecting === false;
    }

    close() {
        const that = this;
        if (!enMqtt || !that.isConnected()) { return; }
        that._subTopic.forEach((topic) => {
            that._client.unsubscribe(topic);
        })
        that._subTopic = [];
        if (that._client){
            that._client.end();
        }
        console.log("mqtt close");
    }

}

export default new MqttUtils();